package com.etone.autotesting.manager.impl;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

import com.etone.autotesting.socketservice.impl.SocketService;
import com.etone.ejb.core.support.Jsoner;

public class ConditionSearchManager {
	
	private final static Logger logger = Logger.getLogger(ConditionSearchManager.class.getName());
	/**
	 * 功能对应的条件,只能一个功能执行
	 */
	private Map functionConditonMap;
	/**
	 * 功能和线程的执行
	 */
	private Map functionRunMap;
	/**
	 * 
	 */
	private ExecutorService pool;
	/**
	 * 
	 */
	private static ConditionSearchManager instance = null;

	/**
	 * 
	 * @return
	 */
	public static ConditionSearchManager getInstance() {
		if (instance == null)
			instance = new ConditionSearchManager();
		return instance;
	}

	public ConditionSearchManager() {
		functionConditonMap = new LinkedHashMap<String, String>();
		functionRunMap = new LinkedHashMap<String, ServiceThreadRunable>();
		pool = Executors.newCachedThreadPool();
	}

	/**
	 * 添加功能的条件
	 * 
	 * @param funCondition
	 * @return
	 * @throws Exception
	 */
	public Boolean addFunctionCondition(String funCondition) throws Exception {
		Jsoner query = new Jsoner(funCondition);
		String functionName = query.find("functionName").getValue();
		if (functionConditonMap.containsKey(functionName)){
			logger.info("SYSTEM||功能名相同，同一个功能只能执行一次！");
			return false;
		}
		functionConditonMap.put(functionName, funCondition);
		Boolean result = createTaskThread(query);
		query=null;
		return result;
	}

	/**
	 * 
	 * @param funCondition
	 * @return
	 */
	private Boolean createTaskThread(Jsoner query) {
		ServiceThreadRunable runable = new ServiceThreadRunable();
		String functionName = query.root().get("functionName").getValue();
		String condition = query.root().get("condition").toString();
		String serviceName = query.root().get("serviceName").getValue();
		String methodName = query.root().get("methodName").getValue();
		String serviceInfo = query.root().get("serviceInfo").getValue();
		runable.setFunction(functionName);
		runable.setCondition(condition);
		runable.setServiceName(serviceName);
		runable.setMethodName(methodName);
		runable.setServiceInfo(serviceInfo);
		functionRunMap.put(functionName, runable);
		pool.execute(runable);
		return true;
	}

}
